/*
* 1videoConference -- An open source video conferencing platform.
*
* Copyright (C) 2007 - 2008, Adiance Technologies Pvt. Ltd.
*
* Hardik Sanghvi <hardik.sanghvi @adiance.com>
*
* See http://www.1videoconference.org for more information about
* the 1videoConference project. Please do not directly contact
* any of the maintainers of this project for assistance;
* the project provides a web site, forums and mailing lists
* for your use.
*
* This program is free software, distributed under the terms of
* the GNU General Public License Version 2. See the LICENSE file
* at the top of the source tree.
*/
using System;
using System.Xml;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Reflection;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Net;
using System.Text;
using Adiance.VMukti.BAL;


namespace prjVCService
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        System.Data.SqlClient.SqlConnection masterConnection = new System.Data.SqlClient.SqlConnection();
        string IpAdd = "";
        System.Diagnostics.EventLog el = new EventLog("application", Environment.MachineName, "ProjectInstaller");

        public ProjectInstaller()
        {
            InitializeComponent();

        }

        public override void Install(System.Collections.IDictionary stateSaver)
        {
            base.Install(stateSaver);

                       
            String strHostName = "";
            IpAdd = ((IPHostEntry)Dns.GetHostByName(strHostName)).AddressList[0].ToString();

            AddDB(IpAdd, this.Context.Parameters["SQLUserName"].ToString().Replace(" ", ""), this.Context.Parameters["SQLPassword"].ToString().Replace(" ", ""));
            EditXML(Context.Parameters["assemblypath"], IpAdd, this.Context.Parameters["SQLUserName"].ToString().Replace(" ", ""), this.Context.Parameters["SQLPassword"].ToString().Replace(" ", ""));

            // System.Diagnostics.Process.Start(Context.Parameters["assemblypath"].Replace("Adiance.VMukti.prjVCService.exe", "") + "setup.exe");

            #region Create Virtual Directory
            string IISPath = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "Adiance");
            System.EnterpriseServices.Internal.IISVirtualRoot vr = new System.EnterpriseServices.Internal.IISVirtualRoot();
            string sError;
            vr.Create("IIS://localhost/W3SVC/1/ROOT", IISPath, "1videoConference", out sError);
            #endregion

            #region Start TCPBinding
            try
            {
                System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo myProcessStartInfo = new System.Diagnostics.ProcessStartInfo("sc.exe");
                myProcessStartInfo.UseShellExecute = false;
                myProcessStartInfo.CreateNoWindow = true;
                myProcessStartInfo.Arguments = "config NetTcpPortSharing start= demand";
                myProcessStartInfo.RedirectStandardError = true;
                myProcess.StartInfo = myProcessStartInfo;
                myProcess.Start();
                myProcess.WaitForExit();
                myProcess.Close();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()1--:----:--");
                Adiance.VMukti.BAL.clsUtility.LogException = ex;
            }
            #endregion

            #region Start VCService
            try
            {
                System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
                System.Diagnostics.ProcessStartInfo myProcessStartInfo = new System.Diagnostics.ProcessStartInfo("net");
                myProcessStartInfo.UseShellExecute = false;
                myProcessStartInfo.CreateNoWindow = true;
                myProcessStartInfo.Arguments = "start VCServer";
                myProcessStartInfo.RedirectStandardError = true;
                myProcess.StartInfo = myProcessStartInfo;
                myProcess.Start();
                myProcess.WaitForExit();
                myProcess.Close();
            }
            catch (Exception ex)
            {
                ex.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()2--:----:--");
                Adiance.VMukti.BAL.clsUtility.LogException = ex;
                //System.Windows.Forms.MessageBox.Show(ex.Message.ToString());
            }
            #endregion

            #region Add Certificate
            string CertiPath = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "Adiance.cer");
            System.Security.Cryptography.X509Certificates.X509Certificate2 Certi = new System.Security.Cryptography.X509Certificates.X509Certificate2();
            Certi.Import(CertiPath);

            System.Security.Cryptography.X509Certificates.X509Store RootCertificate = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.Root, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            RootCertificate.Open(System.Security.Cryptography.X509Certificates.OpenFlags.MaxAllowed);
            RootCertificate.Add(Certi);
            RootCertificate.Close();

            System.Security.Cryptography.X509Certificates.X509Store TrustedRootCertificate = new System.Security.Cryptography.X509Certificates.X509Store(System.Security.Cryptography.X509Certificates.StoreName.TrustedPublisher, System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine);
            TrustedRootCertificate.Open(System.Security.Cryptography.X509Certificates.OpenFlags.MaxAllowed);
            TrustedRootCertificate.Add(Certi);
            TrustedRootCertificate.Close();
            #endregion

            #region Create User
            System.Diagnostics.Process processCreateUser = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo processCreateUserInfo = new System.Diagnostics.ProcessStartInfo("net");
            processCreateUserInfo.UseShellExecute = false;
            processCreateUserInfo.CreateNoWindow = true;
            processCreateUserInfo.RedirectStandardInput = true;
            processCreateUserInfo.RedirectStandardOutput = true;
            processCreateUserInfo.Arguments = "user 1videoConference resiprocket /ADD /FULLNAME:1videoConference /PASSWORDCHG:NO ";
            processCreateUser.StartInfo = processCreateUserInfo;
            processCreateUser.Start();
            processCreateUser.WaitForExit();
            processCreateUser.Close();
            #endregion

            #region Change Password
            System.Diagnostics.Process processChangePass = new System.Diagnostics.Process();
            System.Diagnostics.ProcessStartInfo ProcessChangePassInfo = new System.Diagnostics.ProcessStartInfo("net");
            ProcessChangePassInfo.UseShellExecute = false;
            ProcessChangePassInfo.CreateNoWindow = true;
            ProcessChangePassInfo.RedirectStandardInput = true;
            ProcessChangePassInfo.RedirectStandardOutput = true;
            ProcessChangePassInfo.Arguments = "user 1videoConference resiprocket";
            processChangePass.StartInfo = processCreateUserInfo;
            processChangePass.Start();
            processChangePass.WaitForExit();
            processChangePass.Close();
            #endregion

            #region UriGeneration

            try
            {
                string DefaultUserEmail = this.Context.Parameters["UserEMail"].ToString();
                string DefaultUserPassword = this.Context.Parameters["UserPassword"].ToString();
                string thanksgiving = "Thank You For Installing 1videoConference!!";
                string msg = "Your Superadmin Username is:  " + DefaultUserEmail + " and Your Superadmin Password is: " + DefaultUserPassword + ".";
                SendEmailTo(this.Context.Parameters["SMTPUsername"].ToString(), DefaultUserEmail, thanksgiving, msg);

                string Encode = "mid=1,uname=" + DefaultUserEmail + ",role=Host";
                string hosturl = encodestring(Encode);
                string url = " http://" + IpAdd + "/1videoConference/1videoConference.xbap?" + hosturl;
                string subject = "1videoConference.com Video Conferencing Query";
                StringBuilder sb = new StringBuilder();
                sb.Append("You are now registered with 1videoConference (A rich web based Video Conferencing Solution)");
                sb.Append("&nbsp;");
                sb.Append("&nbsp;");
                sb.Append("<br>");
                sb.Append("<br>");
                sb.AppendLine("You can take part in the meeting by following url" + url);
                sb.Append("<br>");
                sb.Append("<br>");

                sb.Append("<br>");
                sb.Append("<br>");
                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("Login: </b>" + DefaultUserEmail);
                sb.Append("</td>");
                sb.Append("</tr>");

                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("Password: </b>" + DefaultUserPassword);
                sb.Append("</td>");
                sb.Append("</tr>");

                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("Subject: Default Meeting");
                sb.Append("</td>");
                sb.Append("</tr>");

                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("Preferred Date: </b>" + DateTime.Today.Date.ToString());
                sb.Append("</td>");
                sb.Append("</tr>");

                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("Start Time: 00:00");
                sb.Append("</td>");
                sb.Append("</tr>");

                sb.Append("<tr>");
                sb.Append("<td><b>");
                sb.Append("End Time: 23:59 ");
                sb.Append("</td>");
                sb.Append("</tr>"); sb.Append("<table>");

               
                SendEmailTo(this.Context.Parameters["SMTPUsername"].ToString(), DefaultUserEmail, subject, sb.ToString());

                AddDB1(IpAdd, this.Context.Parameters["SQLUserName"].ToString().Replace(" ", ""), this.Context.Parameters["SQLPassword"].ToString().Replace(" ", ""));
            }
            catch (Exception ex)
            {
                el.WriteEntry("Uri Generation " + ex.Message);
                el.Close();
            }
            #endregion
         
        }

        #region Database
        protected void AddDB(string IPAdd, string UserName, string Password)
        {
            try
            {             

                string DBName = "Videoconference";
                SqlCommand command = new SqlCommand("DROP DATABASE " + DBName, masterConnection);
                masterConnection.ConnectionString = (@"Data Source=" + IPAdd + "\\SQLExpress;Initial Catalog=master;User Id=" + UserName + ";Password=" + Password + ";Integrated Security=False");
                //masterConnection.ConnectionString = "server=" + Server + ";uid=" + UserName + ";pwd=" + Password + ";database=master;";
                command.Connection.Open();
                command.Connection.ChangeDatabase("master");
                try
                {
                    command.ExecuteNonQuery();
                    command.Connection.Close();
                }
                catch (Exception ex)
                {
                    el.WriteEntry("AddDB " + ex.Message);
                    el.Close();
                    command.Connection.Close();
                    //exp.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()3--:----:--");
                    //Adiance.VMukti.BAL.clsUtility.LogException = exp;
                }
                string ProjectPath = Context.Parameters["assemblypath"];
                string OperatingDrive = ProjectPath.Remove(ProjectPath.LastIndexOf("//") + 3);
                string LocalPath = ProjectPath.Replace("Adiance.VMukti.VCService.exe", "Adiance");
                string SitePath = ("http://" + IPAdd + "/1videoConference");
                string SiteURL = ("http://" + IPAdd + "/1videoConference/1videoConference.xbap");


                ExecuteSql("master", "CREATE DATABASE " + DBName, IPAdd, UserName, Password);
                ExecuteSql(DBName, GetSql("sql.txt"), IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SMTPServer', '" + this.Context.Parameters["SMTPServer"].ToString().Replace(" ", "") + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SMTPPort', '" + this.Context.Parameters["SMTPPort"].ToString().Replace(" ", "") + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SMTPUserName', '" + this.Context.Parameters["SMTPUsername"].ToString().Replace(" ", "") + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SMTPPassword', '" + this.Context.Parameters["SMTPPassword"].ToString().Replace(" ", "") + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('AsteriskServer', '" + this.Context.Parameters["AsteriskIP"].ToString().Replace(" ", "") + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('LocalPath', '" + LocalPath + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SitePath', '" + SitePath + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('SiteURL', '" + SiteURL + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('DBUser', '" + UserName + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('DBPass', '" + Password + "')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into Config values ('VLCPath', '" + ProjectPath.Replace("\\Adiance.VMukti.VCService.exe","") + "')", IPAdd, UserName, Password);
               
                if (this.Context.Parameters["SSL"].ToString() == "1")
                {
                    ExecuteSql(DBName, "insert into Config values ('SMTPSSL', 'True')", IPAdd, UserName, Password);
                }
                else
                {
                    ExecuteSql(DBName, "insert into Config values ('SMTPSSL', 'False')", IPAdd, UserName, Password);
                }

                ExecuteSql(DBName, "insert into Country ([Country Name]) values ('India')", IPAdd, UserName, Password);
                ExecuteSql(DBName, "insert into State (StateID,CountryID,[State Name]) values ('1','1','Gujarat')", IPAdd, UserName, Password);


                #region To Enter Data in Table Dll
                try
                {
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('1','1videoConference.Audio.Control.dll','1')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('2','Interop.RTCCORELib.dll','1')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('3','1videoConference.Chat.Control.dll','2')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('4','1videoConference.DesktopCtl.Control.dll','3')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('5','1videoConference.Poll.Control.dll','4')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('6','1videoConference.Presentation.Control.dll','5')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('7','1videoConference.QA.Control.dll','6')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('8','1videoConference.Video.Control.dll','7')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('9','DirectX.Capture.dll','7')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('10','DShowNET.dll','7')", IPAdd, UserName, Password);
                    //ExecuteSql(DBName, "insert into Dll ([DllName]) values ('UserInfo.dll')", IPAdd, UserName, Password);
                    //ExecuteSql(DBName, "insert into Dll ([DllName]) values ('NetPeerService.dll')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('11','1videoConference.WebLink.Control.dll','8')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Dll ([DllID],[DllName],[ModuleID]) values ('12','1videoConference.WhiteBoard.Control.dll','9')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("Insert into DLL " + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in Namespace Table
                try
                {
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('1','1','_videoConference.Audio.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('2','3','_videoConference.Chat.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('3','4','_videoConference.DesktopCtl.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('4','5','_videoConference.Poll.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('5','6','_videoConference.Presentation.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('6','7','_videoConference.QA.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('7','8','_videoConference.Video.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('8','11','_videoConference.WebLink.Control','v2.0.50727')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Namespace (NamespaceID,DllID,NamespaceName,NamespaceVersion) values ('9','12','_videoConference.WhiteBoard.Control','v2.0.50727')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into Namespace" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in Class Table
                try
                {
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('1','1','1','Audio')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('2','2','3','Chat')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('3','3','4','DesktopCtl')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('4','3','4','DesktopThumb')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('5','4','5','AudiencePoll')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('6','5','6','Presentation')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('7','6','7','QAControl')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('8','7','8','DirectXVideo')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('9','7','8','UserVideo')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('10','8','11','WebLink')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Class (ClassID,NamespaceId,DllID,ClassName) values ('11','9','12','WhiteBoard')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into Class" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in ZipInfo Table
                try
                {
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('1','Audio','Audio.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('2','Chat','Chat.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('3','Desktop','Desktop.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('4','Poll','Poll.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('5','Presentation','Presentation.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('6','QA','QA.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('7','Video','Video.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('8','Weblink','Weblink.zip')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into ZipInfo ([Module ID],[Module Name],[Zip FileName]) values ('9','Whiteboard','Whiteboard.zip')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into ZipInfo" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in MenuTable
                try
                {
                    ExecuteSql(DBName, "insert into MenuTable (Id,ParentId,Image,MenuCaption,PageName) values ('1','0','NULL','Meeting','Meeting')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into MenuTable (Id,ParentId,Image,MenuCaption,PageName) values ('2','0','NULL','Presentation','Presentation')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into MenuTable (Id,ParentId,Image,MenuCaption,PageName) values ('3','0','NULL','Desktop Sharing','Desktop')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into MenuTable" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in Modules Table
                try
                {
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.Audio.Control.dll','Audio','Audio','1','1')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.Chat.Control.dll','Chat','Chat','3','2')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.DesktopCtl.Control.dll','DesktopCtl','Desktop','4','3')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.Poll.Control.dll','AudiencePoll','Poll','5','4')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.Presentation.Control.dll','Presentation','Presentation','6','5')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.QA.Control.dll','QAControl','QA','7','6')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.Video.Control.dll','DirectXVideo','Video','8','7')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.WebLink.Control.dll','WebLink','Weblink','11','8')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Modules ([Dll Name],[Class Name],[Module Name],[DllID],[ModID]) values ('1videoConference.WhiteBoard.Control.dll','WhiteBoard','WhiteBoard','12','9')", IPAdd, UserName, Password);

                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into Modules" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in Pages Table
                try
                {
                    ExecuteSql(DBName, "insert into Pages ([Page Name],[Page Title],[Page Description],[Menu Designer]) values ('Meeting','Meeting','Meeting','1')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Pages ([Page Name],[Page Title],[Page Description],[Menu Designer]) values ('Presentation','Presentation','Presentation','2')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into Pages ([Page Name],[Page Title],[Page Description],[Menu Designer]) values ('Desktop','Desktop','Desktop','3')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into Pages" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To Enter Data in tblDesignePod
                try
                {
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('1','1','Audio','Audio','45','88','146','79','1')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('5','1','Chat','Chat','244','419','572','19','2')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('4','1','Video','Video','191','551','16','19','7')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('2','1','QA','QA','210','200','576','270','6')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('3','1','Poll','Poll','210','212','779','270','4')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('9','1','Whiteborad','WhiteBoard','183','556','13','217','9')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('8','1','Weblink','Weblink','77','557','14','405','8')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('7','2','Presentation','Presentation','450','918','5','5','5')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblDesignPOD (PodID,Layout_id,PodTitle,ControlName,PodHeight,PodWidth,PodLeft,PODTop,ModID) values ('6','3','Desktop','Desktop','450','918','5','5','3')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into DesignPod" + exp.Message);
                    el.Close();
                }
                #endregion

                #region To enter Data in tblPageLayout
                try
                {
                    ExecuteSql(DBName, "insert into tblPageLayout (Layout_id,Layout_name) values ('1','Meeting')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblPageLayout (Layout_id,Layout_name) values ('2','Presentation')", IPAdd, UserName, Password);
                    ExecuteSql(DBName, "insert into tblPageLayout (Layout_id,Layout_name) values ('3','Desktop')", IPAdd, UserName, Password);
                }
                catch (Exception exp)
                {
                    el.WriteEntry("insert into PageLayout" + exp.Message);
                    el.Close();
                }
                #endregion


            }
            catch (Exception ex)
            {
                el.WriteEntry("AddDB " + ex.Message);
                el.Close();
                //throw ex;
                //ex.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()5--:----:--");
                //Adiance.VMukti.BAL.clsUtility.LogException = ex;
            }
        }

        private void ExecuteSql(string DatabaseName, string sql, string ServerName, string UserName, string Password)
        {
            SqlCommand command = new SqlCommand(sql, masterConnection);
            masterConnection.ConnectionString = (@"Data Source=" + ServerName + "\\SQLExpress;Initial Catalog=master;User Id=" + UserName + ";Password=" + Password + ";Integrated Security=False");
            //masterConnection.ConnectionString = "server=" + ServerName + ";uid=" + UserName + ";pwd=" + Password + ";database=master;";

            command.Connection.Open();
            command.Connection.ChangeDatabase(DatabaseName);
            try
            {
                command.ExecuteNonQuery();
            }
            finally
            {
                command.Connection.Close();
            }
        }

        private string GetSql(string Name)
        {
            try
            {
                Assembly Asm = Assembly.GetExecutingAssembly();
                Stream str = Asm.GetManifestResourceStream(Asm.GetName().Name + "." + Name);
                StreamReader reader = new StreamReader(str);
                return reader.ReadToEnd();
            }
            catch (Exception ex)
            {
                return "";
                ex.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()6--:----:--");
                Adiance.VMukti.BAL.clsUtility.LogException = ex;
            }
        }
        #endregion

        #region Editing XML
        public void EditXML(string path, string IPAdd, string sqlusername, string sqlpassword)
        {
            string assemblypath = Context.Parameters["assemblypath"];
            string appConfigPath = assemblypath + ".config";
            
            XmlDocument doc = new XmlDocument();
            doc.Load(appConfigPath);
            XmlNode configuration = null;
            foreach (XmlNode node in doc.ChildNodes)
                if (node.Name == "configuration")
                    configuration = node;

            if (configuration != null)
            {
                XmlNode settingNode = null;
                foreach (XmlNode node in configuration.ChildNodes)
                    if (node.Name == "appSettings")
                        settingNode = node;

                if (settingNode != null)
                {
                    XmlNode NumNode = null;
                    foreach (XmlNode node in settingNode.ChildNodes)
                    {
                        if (node.Attributes["key"] != null)
                        {
                            if (node.Attributes["key"].Value == "ConnString")
                            {
                                NumNode = node;
                                if (NumNode != null)
                                {
                                    try
                                    {
                                        XmlAttribute att = NumNode.Attributes["value"];
                                        att.Value = "Server=" + IPAdd + "\\SQLExpress;Database=Videoconference;User ID=" + sqlusername + ";Password=" + sqlpassword + ";Trusted_Connection=False;";
                                        //masterConnection.ConnectionString = "server=" + server + ";uid=" + sqlusername + ";pwd=" + sqlpassword + ";database=VideoConf;";
                                        doc.Save(appConfigPath);
                                    }
                                    catch (Exception ex)
                                    {
                                        ex.Data.Add("My Key", "Adiance.VMukti.VCService--:--ProjectInstaller.cs--:--Install()7--:----:--");
                                        Adiance.VMukti.BAL.clsUtility.LogException = ex;
                                        //throw ex;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private void mbox(string assemblypath)
        {
            throw new Exception("The method or operation is not implemented.");
        }
        #endregion

        #region EncodeString
        string encodestring(string str)
        {
            try
            {
                int j = 0;

                Byte[] encodedBytes = ASCIIEncoding.ASCII.GetBytes(str);
                Byte[] ans = new Byte[encodedBytes.Length];
                foreach (Byte b in encodedBytes)
                {

                    int i = Convert.ToInt32(b);

                    if ((i >= 65 && i <= 90) || (i >= 97 && i <= 122))
                    {
                        i += 4;
                        if ((i > 90 && i <= 97) || (i > 122 && i <= 129))
                            i = i - 26;

                    }
                    else if (i >= 48 && i <= 57)
                    {
                        i += 7;
                        if (i > 57)
                            i = i - 10;
                    }
                    else
                    {
                        if (i == 61)
                            i = 44;
                        else if (i == 44)
                            i = 61;
                    }

                    ans[j++] = Convert.ToByte(i);
                }
                return ASCIIEncoding.ASCII.GetString(ans);
            }
            catch (Exception ex)
            {
                el.WriteEntry("Encode String " + ex.Message);
                el.Close();
                //ex.Data.Add("My Key", "1videoConference--:--CreateMeeting.xaml.cs--:--encodestring()--:----:--");
                //clsUtility.LogException = ex;
                //MessageBox.Show("CreateMeeting--:--CreateMeeting.xaml.cs--:-- encodestring() ---" + ex.Message);
                return null;
            }
        }
#endregion

        #region SendMail
        public  void SendEmailTo(string from, string To, string Subject, string msg)
        {
            try
            {
                el.WriteEntry("To " + To);
                el.Close();
                el.WriteEntry("from:" + from);
                el.Close();

                System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage();
                mailMsg.From = new System.Net.Mail.MailAddress(from);
                //mailMsg.From = new MailAddress(UserInfo.ConSMTPUserName);
                mailMsg.To.Add(To);

                mailMsg.Subject = Subject;
                mailMsg.SubjectEncoding = System.Text.Encoding.UTF8;
                mailMsg.Body = msg;
                mailMsg.BodyEncoding = System.Text.Encoding.UTF8;
                mailMsg.Priority = System.Net.Mail.MailPriority.High;
                mailMsg.IsBodyHtml = true;

                //System.Net.Mail.SmtpClient SmtpMail = new System.Net.Mail.SmtpClient(SMTPSer, Convert.ToInt16(SMTPPo));
                System.Net.Mail.SmtpClient SmtpMail = new System.Net.Mail.SmtpClient(Context.Parameters["SMTPServer"], Convert.ToInt16(this.Context.Parameters["SMTPPort"]));
                SmtpMail.Credentials = new System.Net.NetworkCredential(this.Context.Parameters["SMTPUsername"], this.Context.Parameters["SMTPPassword"]);

                if (this.Context.Parameters["SSL"].ToString() == "1")
                {
                    SmtpMail.EnableSsl = true;
                }
                else
                {
                    SmtpMail.EnableSsl = false;
                }

                el.WriteEntry("SSL " + SmtpMail.EnableSsl.ToString());
                el.Close();
                
                try
                {
                    SmtpMail.Send(mailMsg);
                }
                catch (Exception ex)
                {
                    el.WriteEntry("smtpSendMail " + ex.Message);
                    //ex.Data.Add("My Key", "1videoConference--:--CreateMeeting.xaml.cs--:--SendEmailTo()1--:----:--");
                    //clsUtility.LogException = ex;
                    ////MessageBox.Show(ex.Message.ToString());
                }
            }

            catch (Exception ex)
            {
                el.WriteEntry("Send E-Mail " + ex.Message);
                el.Close();
                //ex.Data.Add("My Key", "1videoConference--:--CreateMeeting.xaml.cs--:--SendEmailTo()2--:----:--");
                //clsUtility.LogException = ex;
                ////MessageBox.Show("CreateMeeting--:--CreateMeeting.xaml.cs--:-- SendEmailTo() ---" + ex.Message); 
            }
        }
        #endregion

        #region EditTables

        void AddDB1(string IPAdd, string UserName, string Password)
        {
            string DBName = "Videoconference";
            ExecuteSql(DBName, "insert into UserRegistration (AccId, CountryId, StateId, FName, LName, EMail, Pass,Number) values ('1','1','1','" + this.Context.Parameters["UserEMail"] + "','','" + this.Context.Parameters["UserEMail"] + "','" + this.Context.Parameters["UserPassword"] + "','1110')", IPAdd, UserName, Password);
            ExecuteSql(DBName, "insert into MeetingInformation (AccID,MeetingName,MDate,MTime,MEndTime,MaxParti,MPassword) values ('1','Default Meeting','" + DateTime.Today.Date.ToString() + "','00:00','23:59','0','" + this.Context.Parameters["UserPassword"] + "')", IpAdd, UserName, Password);
        }

        #endregion

        protected override void OnAfterInstall(System.Collections.IDictionary savedState)
        {
            base.OnAfterInstall(savedState);
            
            string ProjectPath = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "");
            string CertiPath = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "Adiance.cer");
            string ModulePath = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "Zip Files");

            #region To Extract Files

            string pathbal = ProjectPath + "Business Layer";
            string pathdal = ProjectPath + "Data Layer";
            string pathview = ProjectPath + "Presentation Layer";
            string pathimage = ProjectPath + "Image";
            string pathtemp = ProjectPath + "Temp";
            string pathsql = ProjectPath + "SQL Scripts";


            Directory.CreateDirectory(pathbal);
            Directory.CreateDirectory(pathdal);
            Directory.CreateDirectory(pathview);
            Directory.CreateDirectory(pathimage);
            Directory.CreateDirectory(pathtemp);
            Directory.CreateDirectory(pathsql);


            string[] ZipCount = Directory.GetFiles(ModulePath);

            Adiance.VMukti.ZipUnzip.Zip.FastZip fz = new Adiance.VMukti.ZipUnzip.Zip.FastZip();
            for (int i = 0; i < ZipCount.Length; i++)
            {
                string[] strsplit = ZipCount[i].Split('\\');
                string[] strmodulename = strsplit[strsplit.Length - 1].Split('.');
                string modulename = strmodulename[0].ToString();

                fz.ExtractZip(ZipCount[i], pathtemp, null);

                Directory.CreateDirectory(pathview + "\\" + modulename);
                Directory.CreateDirectory(pathdal + "\\" + modulename);
                Directory.CreateDirectory(pathbal + "\\" + modulename);

                string[] dirnameorg = Directory.GetDirectories(pathtemp);
                string[] dirname = Directory.GetDirectories(dirnameorg[0]);

                for (int k = 0; k < dirname.Length; k++)
                {
                    string[] strSplit = dirname[k].ToString().Split('\\');

                    if (strSplit[strSplit.Length - 1].ToUpper() == "BAL")
                    {
                        string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                        for (int j = 0; j < balfilenames.Length; j++)
                        {
                            string[] filefoldername = balfilenames[j].Split('\\');
                            File.Copy(balfilenames[j], pathbal + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                        }

                    }

                    if (strSplit[strSplit.Length - 1].ToUpper() == "DAL")
                    {
                        string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                        for (int j = 0; j < balfilenames.Length; j++)
                        {
                            string[] filefoldername = balfilenames[j].Split('\\');
                            File.Copy(balfilenames[j], pathdal + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                        }

                    }

                    if (strSplit[strSplit.Length - 1].ToUpper() == "CONTROL")
                    {
                        string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                        for (int j = 0; j < balfilenames.Length; j++)
                        {
                            string[] filefoldername = balfilenames[j].Split('\\');
                            File.Copy(balfilenames[j], pathview + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                        }
                        if (modulename == "VLCVideo")
                        {
                            fz.ExtractZip(pathview + "\\" + modulename + "\\VideoEXE.zip", pathview + "\\" + modulename, null);
                        }

                    }

                    if (strSplit[strSplit.Length - 1].ToUpper() == "IMAGES")
                    {
                        string[] balfilenames = Directory.GetFiles(dirname[k].ToString());
                        for (int j = 0; j < balfilenames.Length; j++)
                        {
                            string[] filefoldername = balfilenames[j].Split('\\');
                            File.Copy(balfilenames[j], pathimage + "\\" + modulename + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                        }

                    }

                    if (strSplit[strSplit.Length - 1].ToUpper() == "SQL")
                    {
                        string[] baldirnames = Directory.GetDirectories(dirname[k].ToString());
                        for (int dircount = 0; dircount < baldirnames.Length; dircount++)
                        {
                            string[] files = baldirnames[dircount].Split('\\');
                            Directory.CreateDirectory(pathsql + "\\" + modulename + "\\" + files[files.Length - 1].ToString());
                            string[] sqlfilenames = Directory.GetFiles(baldirnames[dircount]);
                            for (int j = 0; j < sqlfilenames.Length; j++)
                            {
                                string[] filefoldername = sqlfilenames[j].Split('\\');
                                File.Copy(sqlfilenames[j], pathsql + "\\" + modulename + "\\" + files[files.Length - 1].ToString() + "\\" + filefoldername[filefoldername.Length - 1].ToString());
                            }
                        }
                    }
                }
                Directory.Delete(dirnameorg[0], true);
            }

            #endregion

            #region For .NET FrameWork 3.0
            //string path = (Context.Parameters["assemblypath"].Replace("WindowsService1.exe", "") + "Redist_dotnetfx3_x86.exe");
            //myProc.StartInfo.FileName = @"D:\Nisarg\Softwares\SkypeSetup.exe";
            //myProc.Start();

            //string path = Context.Parameters["assemblypath"].Remove(3);
            //string WinFxPath = path + @"WINDOWS\Microsoft.NET\Framework\v3.0\Microsoft .NET Framework 3.0 x86";

            //if (!Directory.Exists(WinFxPath))
            //{
            //    System.Diagnostics.Process.Start(Context.Parameters["assemblypath"].Replace("WindowsService1.exe", "") + "Redist_dotnetfx3_x86.exe");
            //}
            #endregion

        }

        public override void Uninstall(System.Collections.IDictionary savedState)
        {
            base.Uninstall(savedState);
            try
            {
                string temp = Context.Parameters["assemblypath"].Replace("Adiance.VMukti.VCService.exe", "");
                string bal = temp + "\\Data Layer";
                string dal = temp + "\\Image";
                string image = temp + "\\Business Layer";
                string presentation = temp + "\\Presentation Layer";
                string sql = temp + "\\SQL Scripts";
                string tempfolder = temp + "\\Temp";

                try { Directory.Delete(bal, true); }
                catch { }

                try { Directory.Delete(dal, true); }
                catch { }

                try { Directory.Delete(image, true); }
                catch { }

                try { Directory.Delete(presentation, true); }
                catch { }

                try { Directory.Delete(sql, true); }
                catch { }

                try { Directory.Delete(tempfolder, true); }
                catch { }
            }
            catch
            { }
        }

    }
}